package com.mbigger.admin.dao;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.mbigger.admin.entity.Department;
/**
 * 部门
 * @author mbigg
 *
 */
@Mapper
public interface DeptMapper {
	
	@Delete("DELETE FROM sys_dept WHERE id=#{id}")
	int deleteById(@Param("id")Integer id);
	
	@Insert("INSERT INTO sys_dept (name, parent_id, level, seq, remark, operator, operate_time, operate_ip) "
			+ "VALUES (#{name}, #{parentId}, #{level}, #{seq}, #{remark}, #{operator}, #{operateTime}, #{operateIp})")
	@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
	int insert(@Param("dept")Department dept);
	
	@Select("SELECT * FROM sys_dept where id=#{id}")
	Department selectById(@Param("id")Integer id);
	
	@Update("UPDATE sys_dept SET name=#{name}, parent_id=#{parentId}, level=#{level}, seq=#{seq}, remark=#{remark}, operator=#{operator}, operate_time=#{operateTime}, operate_ip=#{operateIp} WHERE id=#{id}")
	int updateById(@Param("dept")Department dept);

	@Select("SELECT * FROM sys_dept")
	List<Department> getAllDept();
	
	@Select("SELECT * FROM sys_dept WHERE level LIKE #{level}")
	List<Department> getChildDeptListByLevel(@Param("level")String level);
	
	@Update("<script>"
			+ "<foreach collection='deptList' item='dept' open='(' close=')' separator=';'>"
			+ "UPDATE sys_dept SET level=#{dept.level} WHERE id=#{dept.id}"
			+ "</foreach>"
			+ "</script>")
	void batchUpdateLevel(@Param("deptList")List<Department> deptList);
	
	@Select("<script>"
			+ "SELECT count(1) "
			+ "FROM sys_dept "
			+ "WHERE name=#{name}"
			+ "<if test='parentId != null'>"
			+ "AND parent_id!=#{parentId}"
			+ "</if>"
			+ "<if test='id != null'>"
			+ "AND id!=#{id}"
			+ "</if>"
			+ "</script>")
	int countByNameAndParentId(@Param("parentId")Integer parentId, @Param("name")String name,  @Param("id")Integer id);
	
	@Select("SELECT count(1) FROM sys_dept WHERE parent_id=#{deptId}")
	int countByParentId(@Param("deptId")int deptId);
}
